<?php

class Application_Model_UserMapper {
	
	protected $_dbTable;
	protected $_passSalt = 'ce8d96d579d389e783f95b3772785783ea1a9854';
	
	public function setDbTable($dbTable){
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_User');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_User $user){
		$data = array(
				'first_name'   => $user->getFirst_name(),
				'last_name' => $user->getLast_name(),
				'email' => $user->getEmail(),
				'password' => sha1($user->getPassword().$this->_passSalt),
				'password_salt' => $this->_passSalt,
				'address' => $user->getAddress(),
				'is_admin' => $user->getIs_admin()
		);
	
		if (null === ($id = $user->getId_user())) {
			unset($data['id_user']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id_user = ?' => $id));
		}
	}
	
	public function find($id, Application_Model_User $user){
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$user->setId_user($row->id_user)
			->setEmail($row->email)
			->setFirst_name($row->first_name)
			->setLast_name($row->last_name)
			->setAddress($row->address)
			->setIs_admin($row->is_admin)
			->setId_cart($row->id_cart);
	}
	
	public function fetchAll() {
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_User();
			$entry->setId_user($row->id_user)
				->setEmail($row->email)
				->setFirst_name($row->first_name)
				->setLast_name($row->last_name)
				->setAddress($row->address)
				->setIs_admin($row->is_admin)
				->setId_cart($row->id_cart);
			$entries[] = $entry;
		}
		return $entries;
	}
	
	public function getByCart($idCart){
		$row = $this->getDbTable()->fetchRow(array(" id_cart = ?"=>$idCart));
		$user = new Application_Model_User();
		$user->setId_user($row->id_user)
				->setEmail($row->email)
				->setFirst_name($row->first_name)
				->setLast_name($row->last_name)
				->setAddress($row->address)
				->setIs_admin($row->is_admin)
				->setId_cart($row->id_cart);
		return $user;
	}
	
	public function delete($id){
		$where = $this->getDbTable()->getAdapter()->quoteInto('id_user = ?', $id);
		return $this->getDbTable()->delete($where);
	}

}

